package com.jiazhong.cloud.gateway.example.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.jiazhong.cloud.commons.bean.Power;
import com.jiazhong.cloud.commons.config.JwtConfig;
import com.jiazhong.cloud.commons.util.JsonResult;
import com.jiazhong.cloud.commons.util.ResultTool;
import com.jiazhong.cloud.gateway.example.gateway.service.PowerService;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

// 是否具有对应权限过滤器
@Component
@Slf4j
public class IsAccessGlobalFilter implements Ordered, GlobalFilter {

    private StringRedisTemplate stringRedisTemplate;
    private ValueOperations<String, String> valueOperations;
    private PowerService powerService;

    @Autowired
    public IsAccessGlobalFilter(StringRedisTemplate stringRedisTemplate, PowerService powerService) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.powerService = powerService;
        valueOperations = stringRedisTemplate.opsForValue();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始校验用户是否有对应的权限");
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        log.info("用户访问的路径是：{}", uri.getPath());
        if (uri.getPath().contains("/auth")) {
            log.info("用户访问登陆接口，不需要登陆，直接访问！");
            return chain.filter(exchange);
        }
        // 获取到用户的id
        String token = request.getHeaders().get("token").get(0);
        Claims claims = JwtConfig.parseJWT(token);
        String id = claims.get("id").toString();
        // 获取到用户的对应权限
        JsonResult<List<Power>> powers = powerService.findPowersByStudentId(id);
        // 验证是否具有对象权限
        String path = exchange.getRequest().getURI().getPath();
        AtomicBoolean b = new AtomicBoolean(false);
        powers.getData().forEach(e -> {
            String url = e.getPowerUrl();
            boolean contains = path.contains(url);
            if (contains) {
                b.set(true);
            }
        });
        if (!b.get()) {
            return fail(exchange);
        }
        return chain.filter(exchange);
    }

    @SneakyThrows
    private Mono<Void> fail(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(403, "用户没有权限访问");
        String str = JSONArray.toJSONString(result);
        DataBuffer data =
                response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
